package com.abc.core.tool;

import com.abc.core.instance.bo.Cell;
import com.abc.core.instance.bo.Inst;
import com.abc.core.service.InstService;
import com.abc.demo.PartyAccountBO;
import com.abc.demo.PartyBO;

/**
 * 2.4.1 元数据实例与POJO定制化转换
 */
public class PartyHelper {

    private InstService instService;

    public Inst partyBO2Inst(PartyBO party) {
        Inst partyInst = this.instService.initInst("part_dna");
        Cell partyCell = partyInst.getSingleCell();
        partyCell.setId(party.getId());
        partyCell.setVaByName("partyName", party.getPartyName());
        partyCell.setVaByName("certType", party.getCertType());
        partyCell.setVaByName("certId", party.getCertId());
        partyCell.setVaByName("contact", party.getContract());
        partyCell.setVaByName("address", party.getAddress());

        Inst accountInst = instService.initInst("part_account_dna");
        accountInst.getCells().clear();

        for (PartyAccountBO account : party.getAccounts()) {
            Inst tmpAccountInst = instService.initInst("part_account_dna");
            Cell tmpCell = tmpAccountInst.getSingleCell();
            tmpCell.setId(account.getId());
            tmpCell.setVaByName("accountName", account.getAccountName());
            tmpCell.setVaByName("accountNo", account.getAccountNo());
            tmpCell.setVaByName("bankName", account.getBankName());
            accountInst.addCell(tmpCell);
        }

        partyCell.addChildInst(accountInst);
        return partyInst;
    }

    public PartyBO inst2PartyBO(Inst partyInst) {
        PartyBO party = new PartyBO();
        Cell partyCell = partyInst.getSingleCell();
        party.setId(partyCell.getId());
        party.setPartyName(partyCell.getRawStringByName("partyName"));
        party.setCertType(partyCell.getRawStringByName("certType"));
        party.setCertId(partyCell.getRawStringByName("certId"));
        party.setContract(partyCell.getRawStringByName("contact"));
        party.setAddress(partyCell.getRawStringByName("address"));

        Inst accountInst = partyCell.getChildInst("part_dna");
        if (accountInst != null && !accountInst.getCells().isEmpty()) {
            for (Cell cell : accountInst.getCells()) {
                PartyAccountBO account = new PartyAccountBO();
                account.setId(cell.getId());
                account.setAccountName(cell.getRawStringByName("accountName"));
                account.setAccountNo(cell.getRawStringByName("accountNo"));
                account.setBankName(cell.getRawStringByName("bankName"));

                party.getAccounts().add(account);
            }
        }

        return party;
    }
}
